package io.terminus.configuration;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.*;
import io.terminus.handler.DynamicTableNameHandler;
import io.terminus.handler.CustomTenantHandler;
import io.terminus.handler.FieldAutoFillHandler;
import io.terminus.injector.CustomSqlInjector;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * Mybatis Plus配置项
 *
 * @author Melo
 */
@Configuration
public class MybatisPlusAutoConfiguration {

    /**
     * Mybatis Plus插件
     *
     * PerformanceInterceptor性能分析插件已经废弃并移除，如要实现可引用三方插件。如官方推荐的p6spy。该插件有性能消耗，生产环境不建议使用
     *  具体实现可参考https://kaven.blog.csdn.net/article/details/109147219
     *
     * @return Mybatis Plus分页插件拦截器
     */
    @Bean
    @ConditionalOnMissingBean
    public MybatisPlusInterceptor paginationInnerInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        // 分页插件
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        // 乐观锁插件
        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        // 防止全表更新与删除插件
        mybatisPlusInterceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        // 多租户插件
        mybatisPlusInterceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new CustomTenantHandler()));
        // 动态表名插件
        Map<String, TableNameHandler> tableNameHandlerMap = new HashMap<>(1);
        tableNameHandlerMap.put("user", new DynamicTableNameHandler());
        mybatisPlusInterceptor.addInnerInterceptor(new DynamicTableNameInnerInterceptor(tableNameHandlerMap));

        return mybatisPlusInterceptor;
    }

    /**
     * Mybatis Plus自动填充
     * @return 公共字段自动填充处理类
     */
    @Bean
    @ConditionalOnMissingBean
    public FieldAutoFillHandler fieldAutoFillHandler() {
        return new FieldAutoFillHandler();
    }

    /**
     * Mybatis Plus SQL注入器
     * @return 自定义SQL注入器
     */
    @Bean
    public ISqlInjector customSqlInjector() {
        return new CustomSqlInjector();
    }
}
